package com.hjh.net

import android.content.Context
import com.chuckerteam.chucker.api.ChuckerCollector
import com.chuckerteam.chucker.api.ChuckerInterceptor
import com.drake.net.NetConfig
import com.drake.net.cookie.PersistentCookieJar
import com.drake.net.interceptor.LogRecordInterceptor
import com.drake.net.okhttp.setConverter
import com.drake.net.okhttp.setDebug
import com.drake.net.okhttp.setDialogFactory
import com.drake.net.okhttp.setErrorHandler
import com.drake.tooltip.dialog.BubbleDialog
import com.hjh.net.serialization.SerializationConverter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.Cache
import java.io.File
import java.util.concurrent.TimeUnit

/**
 * @author： hjh
 * @createDate： 2025/6/19 10:25
 * @description：
 * @qq： 3472903821
 * @version: 1.0
 */
object Nets {

    fun initNet(context: Context, cacheDir: File, debug: Boolean) {
        CoroutineScope(Dispatchers.Default).launch {
            NetConfig.initialize {
                cookieJar(PersistentCookieJar(context))
                connectTimeout(10, TimeUnit.SECONDS)
                readTimeout(30, TimeUnit.SECONDS)
                writeTimeout(30, TimeUnit.SECONDS)

                cache(
                    Cache(
                        cacheDir,
                        1024 * 1024 * 128
                    )
                )

                setDebug(debug)

                addInterceptor(HeaderInterceptor())
                addInterceptor(LogRecordInterceptor(debug))
                if (debug) {
                    addInterceptor(
                        ChuckerInterceptor.Builder(context)
                            .collector(ChuckerCollector(context))
                            .maxContentLength(250000L)
                            .redactHeaders(emptySet())
                            .alwaysReadResponseBody(false)
                            .build()
                    )
                }

                setDialogFactory {
                    BubbleDialog(context, "加载中")
                }
                setConverter(SerializationConverter())
                setErrorHandler(NetworkErrorHandler())
            }
        }
    }
}